var promisify = require('util').promisify;
var fs = require('fs');
var path = require('path');
const status = promisify(fs.stat);
const readDir = promisify(fs.readdir);
const handlebars = require('handlebars');
const tplPath = path.join(__dirname, '../template/dir.tpl');
const source = fs.readFileSync(tplPath);
var template = handlebars.compile(source.toString());
module.exports.readFileUtil = async function (req, res, filePath) {
const stat = await status(filePath).catch(Error);
  //获取文件
  try {
    if (stat.isFile()) {
      fs.createReadStream(filePath).pipe(res);
      return;
    } else {
      const files = await readDir(filePath);
      // res.statusCode = 200;
      // res.setHeader('Content-type', 'text/html');
      var dir=path.relative(process.cwd(), filePath);
      res.writeHead(200, {
        'Content-Type': 'text/html'
      });
      const data = {
        files,
        title : path.basename(filePath),
        dir : dir ? '/'+dir : ''
      }
      console.log(data.dir);
      res.end(template(data));
      return;
    }
  } catch (err) {
    console.info(err);
    res.writeHead(404, {
      'Context-Type': 'text/html'
    });
    res.end(filePath + ' file is not a directory or file');
    return;
  }
}